(function () {

    var map, converLayer;

    function initMap() {
        var baselayer = new ol.layer.Tile({
            source: new ol.source.XYZ({
                // url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}'
                url: 'http://192.168.101.75:8889/api161/tilemap_1/rest/services/SZIMAGE/SZAVI201712_20ZW2K/ImageServer/tile/{z}/{y}/{x}'
            })
        });

        map = new ol.Map({
            target: 'map',
            layers: [baselayer],
            view: new ol.View({
                projection: 'EPSG:4326',
                center: [112, 36],
                zoom: 6
            })
        });

        var mystyle = new ol.style.Style({
            fill: new ol.style.Fill({
                color: "rgba(72,61,139, 0.4)",
            }),
            stroke: new ol.style.Stroke({
                color: "#1fbd52",
                width: 2
            })
        });
        // converLayer = new ol.layer.Vector({
        //     source: new ol.source.Vector({
        //         url: './data/shanxi_Line.json',
        //         format: new ol.format.GeoJSON()
        //     }),
        //     style: mystyle
        // });
        converLayer = new ol.layer.Vector();
        map.addLayer(converLayer);

    }

    //todo
    //添加遮罩
    function addconver(data) {
        $.getJSON(data, function (data) {
            var fts = (new ol.format.GeoJSON()).readFeatures(data);
            // var fts = (new ol.format.GeoJSON()).readFeatures(geojsonObject);
            var ft = fts[0];
            if (ft) {
                var converGeom = erase(ft.getGeometry());
            }

            var convertFt = new ol.Feature({
                geometry: converGeom
            })
            converLayer.getSource().addFeature(convertFt);
        })
    }

    // 擦除操作,生产遮罩范围
    function erase(data) {
        $.getJSON(data, function(data) {
            var fts = (new ol.format.GeoJSON()).readFeatures(data);
            var ft = fts[0];
            var geom = ft.getGeometry()
            if (geom) {
                var extent = [-180, -90, 180, 90];
                var polygonRing = ol.geom.Polygon.fromExtent(extent);
                var coords = geom.getCoordinates();
                coords.forEach(coord => {
                    var linearRing = new ol.geom.LinearRing(coord[0]);
                    polygonRing.appendLinearRing(linearRing);
                })
                return polygonRing;
            }
        })

    }



    //添加遮罩
    function clipmap(data) {
        $.getJSON(data, function(data) {
            var fts = (new ol.format.GeoJSON()).readFeatures(data);
            var ft = fts[0];
            var converGeom =ft.getGeometry()
            // converGeom.applyTransform(ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
            converGeom.applyTransform(ol.proj.getTransform('EPSG:4490', 'EPSG:3857'));

            //var convertFt =new  ol.Feature(converGeom);
            //converLayer.getSource().addFeature(convertFt);
            var center,pixelScale,offsetX,offsetY,rotation;
            map.on('precompose',function(evt) {
                var canvas=evt.context;
                canvas.save();

                var coords=converGeom.getCoordinates();
                var frameState = evt.frameState;
                var pixelRatio = frameState.pixelRatio;
                var viewState = frameState.viewState;
                center = viewState.center;
                var resolution = viewState.resolution;
                rotation = viewState.rotation;
                var size = frameState.size;
                var size1=map.getSize();
                offsetX = Math.round(pixelRatio * size[0] / 2);
                offsetY = Math.round(pixelRatio * size[1] / 2);
                pixelScale = pixelRatio / resolution;

                canvas.beginPath();
                if(converGeom.getType() == 'MultiPolygon'){
                    for(var i=0;i<coords.length;i++){
                        createClip(coords[i][0], canvas);
                    }
                }
                else if(converGeom.getType() == 'Polygon'){
                    createClip(coords[0], canvas);
                }
                canvas.backgroundColor="red";
                canvas.clip();
            });

            function createClip(coords, canvas) {
                for (var i = 0, cout = coords.length; i < cout; i++) {
                    var xLen = Math.round((coords[i][0] - center[0]) * pixelScale);
                    var yLen = Math.round((center[1] - coords[i][1]) * pixelScale);
                    var x = offsetX;
                    var y = offsetY;
                    if (rotation) {
                        x = xLen * Math.cos(rotation) - yLen * Math.sin(rotation) + offsetX;
                        y = xLen * Math.sin(rotation) + yLen * Math.cos(rotation) + offsetY;
                    } else {
                        x = xLen + offsetX;
                        y = yLen + offsetY;
                    }
                    if (i == 0) {
                        canvas.moveTo(x, y);
                    } else {
                        canvas.lineTo(x, y);
                    }
                }
                canvas.closePath();

            }


            map.on('postcompose', function(event) {
                var ctx = event.context;
                ctx.restore();
            });



        })
    }



    initMap();
    // var dataURL = './data/hubei.geojson'
    // var dataURL = './data/hubei.json'
    var dataURL = './data/gmxq.json'
    // addconver(dataURL);

    clipmap(dataURL);

    setTimeout(()=>{
      let resutl=  erase(dataURL);
        console.log("哈哈哈",resutl)
    },3000)

})();
